import { IStorage, AbstractStorage } from "./IStorage";

export class MemoryStorage extends AbstractStorage {
  private container: Map<string, string | object>;
  constructor(namespace: string) {
    super(namespace);
    this.container = new Map();
  }

  implLoadString(key: string): string | undefined {
    const value = this.container.get(key);
    if (undefined === value) {
      return undefined;
    }

    if (typeof value === 'string') {
      return value;
    }
    else {
      return undefined;
    }
  }

  implSaveString(key: string, value: string): boolean {
    let ret = true;
    if (this.container.has(key)) {
      ret = false; 
    }

    this.container.set(key, value);
    return ret;
  }

  implLoadObject(key: string): object {
    const value = this.container.get(key);
    if (undefined === value) {
      return undefined;
    }

    if (typeof value === 'object') {
      return value;
    }
    else {
      return undefined;
    }
  }

  implSaveObject(key: string, value: object): boolean {
    let ret = true;
    if (this.container.has(key)) {
      ret = false; 
    }

    this.container.set(key, value);
    return ret;
  }

  implHas(key: string): boolean {
    return this.container.has(key);
  }

  implDelete(key: string): string | object | undefined {
    const value = this.container.get(key);
    if (value) {
      this.container.delete(key);
    }
    return value;
  }

  clear(): boolean {
    this.container.clear();
    return true;
  }

  size(): number {
    return this.container.size;
  }
}

